/*
 * Creater:     shizi
 * CreateDate:  2022/03/31
 * Describe：   单位
 * */
import React, { Component } from 'react';
import { Form, Table, Popconfirm, Divider, Button, Select, Input, message, Switch, DatePicker } from 'antd';
import { Util, dayFormat, dateFormat } from 'tools/index';
import moment from 'moment';
import '../style/new-drug.less';

const EditableContext = React.createContext();

class EditableCell extends React.Component {
  renderInput = () => {
    const {
      inputType,
      detailitem,
      disabled,
      onSelect,
      loading,
      descindex,
      desccodeindex,
      valueindex,
      search,
      showTime,
      disableddate
    } = this.props;
    if (inputType === 'SearchSelect') { // 搜索下拉框
      return (
        <Select
          style={{ width: '80%' }}
          allowClear={loading === 'Y' ? false : true} // 与loading效果互斥
          showSearch
          placeholder="请输入"
          defaultActiveFirstOption={false}
          showArrow={false}
          filterOption={false}
          disabled={(disabled === 'Y' || disabled === true) ? true : false}
          onSearch={search || null}
          notFoundContent={null}
          loading={loading === 'Y' ? true : false}
        >
          {detailitem && Array.isArray(detailitem) && detailitem.map((childItem, childIndex) => {
            let descripts = descindex ? childItem[descindex] : childItem.descripts;
            let titleCode = desccodeindex ? childItem[desccodeindex] : childItem.descriptsSPCode;
            return (
              <Option
                value={valueindex ? childItem[valueindex] : childItem.id}
                key={childIndex}
                title={descripts}
                seachprop={descripts + '^' + titleCode}
              >
                {descripts}
              </Option>
            )
          })}
        </Select>
      )
    } else if (inputType === 'Select') {
      return (
        <Select
          allowClear
          showSearch
          optionFilterProp="seachprop"
          placeholder="请选择"
          style={{ width: '80%' }}
          disabled={(disabled === 'Y' || disabled === true) ? true : false}
          onSelect={onSelect || null}
          onClick={this.handlePopconfirm}
        >
          {React.$SelectOptions(detailitem || [], 'descripts')}
        </Select>
      );
    } else if (inputType === 'Input') {
      return (
        <Input
          style={{ width: '80%' }}
          placeholder="请输入"
          disabled={(disabled === 'Y' || disabled === true) ? true : false}
          onClick={this.handlePopconfirm}
        />
      );
    } else if (inputType === 'Switch') {
      return (
        <Switch
          checkedChildren="是"
          unCheckedChildren="否"
          disabled={(disabled === 'Y' || disabled === true) ? true : false}
        />
      )
    } else if (inputType === 'DatePicker' || inputType === 'Date') {
      return (
        <DatePicker
          style={{ width: '80%' }}
          disabled={(disabled === 'Y' || disabled === true) ? true : false}
          showTime={showTime === 'Y' ? true : false}
          format={showTime === 'Y' ? dateFormat : dayFormat}
          disabledDate={disableddate ? this[disableddate] : null} // 限制日期选择
        />
      )
    } else {
      return (
        <Input
          style={{ width: '80%' }}
          type="number"
          className="input-number"
          placeholder="请输入"
          disabled={(disabled === 'Y' || disabled === true) ? true : false}
          onClick={this.handlePopconfirm}
        />
      );
    }
  };

  // 点击删除时阻止事件冒泡
  handlePopconfirm = (e) => {
    e.stopPropagation();
  };

  // 开始日期不能选择今天和之前的日期
  disabledStDate = (current) => {
    return current && current < moment().endOf('day');
  }

  // 结束日期不能选择今天之前的日期
  disabledEndDate = (current) => {
    return current && current < moment(new Date(Date.parse(new Date()) - 86400000)).endOf('day');
  }

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      required,
      title,
      inputType,
      record,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (inputType === 'Switch' ? (
          <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(dataIndex, {
              valuePropName: 'checked',
              initialValue: record[dataIndex] && record[dataIndex] === 'Y' ? true : false
            })(
              this.renderInput()
            )}
          </Form.Item>
        ) : (
          <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(dataIndex, {
              initialValue: record[dataIndex] ? ((inputType === 'DatePicker' || inputType === 'Date' || inputType === 'Time') ? moment(record[dataIndex]) : record[dataIndex]) : undefined,
              rules: [{
                required: required === 'Y' ? true : false,
                message: '必填字段不能为空',
              }],
            })(this.renderInput())}
          </Form.Item>
        )) : (
          children
        )
        }
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

class UnitMaintenance extends Component {
  constructor(props) {
    super(props);
    var userData = JSON.parse(window.sessionStorage.userData);
    this.state = {
      userData,
      columns: [],
      tableData: [],
      editingKey: '',
      rowID: '',
    }
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    //该方法内禁止访问this
    if (('columns' in nextProps && (JSON.stringify(nextProps.columns) !== JSON.stringify(prevState.columns)))) {
      //通过对比nextProps和prevState，返回一个用于更新状态的对象
      return {
        columns: nextProps.columns
      }
    }
    //不需要更新状态，返回null
    return null
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
  }

  // 获取表格数据
  getTableData = (data, isClearRowID) => {
    let dataSource = data && data.length > 0 ? JSON.parse(JSON.stringify(data)) : [];
    for (var i = 0; i < dataSource.length; i++) {
      dataSource[i].key = i + 1;
    }
    this.setState({ tableData: dataSource, rowID: isClearRowID === 'N' ? this.state.rowID : '', editingKey: '' });
  }

  // 新增表格数据
  handleAddTableData = () => {
    const { baseUnitDesc, confirmBeforeAdd } = this.props;
    const { columns, tableData, editingKey } = this.state;
    if (confirmBeforeAdd && confirmBeforeAdd() === 'N') return; // 验证不通过不往下新增
    if (editingKey) {
      message.error("避免数据丢失，请先保存表格其他行数据。");
      return;
    }
    let leg = tableData && tableData.length ? tableData.length + 1 : 1;
    let newData = {
      key: leg
    };
    let newBaseUnitDesc = tableData && tableData.length > 0 ? tableData[0].baseUnitDesc : baseUnitDesc;
    for (var i = 0; i < columns.length; i++) {
      newData[columns[i].dataIndex] = '';
      if (columns[i].dataIndex === 'baseUnitDesc') { // 对照单位
        newData[columns[i].dataIndex] = newBaseUnitDesc || '';
      }
    }
    this.setState({
      tableData: [...tableData, newData]
    }, () => {
      if (!this.state.editingKey) {
        this.setState({ editingKey: leg })
      }
    });
  }

  handleOnRow = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '') {
          // 保存行数据以及ID
          this.setState({ rowID: record.key }, () => {
            this.props.handleRowClick && this.props.handleRowClick(record)
          });
        } else {
          if (this.state.rowID !== record.key) {
            this.setState({ rowID: record.key }, () => {
              this.props.handleRowClick && this.props.handleRowClick(record)
            });
          } else {
            this.setState({ rowID: '' }, () => {
              this.props.handleRowClick && this.props.handleRowClick({})
            });
          }
        }
      },
      onDoubleClick: () => {
        this.props.form.resetFields();
        this.handleEdit({}, record.key, record);
      }
    }
  }
  // 表格行的类名
  setRowClassName = (record) => {
    return this.props.handleRowClick && (record.key === this.state.rowID) ? 'clickRowStyle' : '';
  };

  isEditing = record => record.key === this.state.editingKey;

  // 取消
  handleCancel = (record, e) => {
    record = {
      ...this.formDataFormatConversion(record)
    }
    e?.stopPropagation();
    let currentRowData = this.props.form.getFieldsValue();
    if ('baseUnitDesc' in currentRowData && currentRowData.baseUnitDesc) {
      currentRowData.baseUnitDesc = '';
    }
    let status = Util.checkAttributeIsEmpty(currentRowData);
    if (status) {
      // 都为空则删除该条记录
      this.setState({ editingKey: '' }, () => {
        this.handleDelete(record);
      })
    } else {
      this.setState({ editingKey: '' })
    }
  };

  // 保存行数据
  handleRowSave = (e, form, key) => {
    // saveoperation - 运算所需字段
    // operationSymbol - 运算符号
    let { saveoperation, operationSymbol } = this.props;
    e.stopPropagation && e.stopPropagation();
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const newData = JSON.parse(JSON.stringify(this.state.tableData));
      const index = newData.findIndex(item => key === item.key);
      row = {
        ...this.formDataFormatConversion(row),
      }; // 数据转化

      // 保存前运算
      if (saveoperation) {
        let savesplit = saveoperation && saveoperation.indexOf('=') > -1 ? saveoperation.split('=') : [];
        let saveTotal = savesplit && savesplit.length > 0 ? savesplit[0] : '';
        let paramArr = savesplit && savesplit.length > 1 ? savesplit[1].split('^') : [];
        let operationResult;
        for (var i = 0; i < paramArr.length; i++) {
          if (i === 0) {
            operationResult = (((Number(row[paramArr[0]])).toFixed(2)) * 1000);
            continue;
          }
          if (operationSymbol === '*') {
            operationResult *= (((Number(row[paramArr[i]]).toFixed(2))) * 1000);
            continue;
          }
        }
        row[saveTotal] = operationResult ? (operationResult / (10 ** (3 * paramArr.length))).toFixed(2) : 0;
      }
      if (index > -1) {
        const item = newData[index];
        let currentRowData = {
          ...item,
          ...row
        };
        newData.splice(index, 1, currentRowData);
        this.setState({ tableData: newData, editingKey: '', rowID: currentRowData?.key }, () => {
          this.props.handleRowClick && this.props.handleRowClick(currentRowData);
          this.props.handleSave && this.props.handleSave(this.state.tableData);
        });
      } else {
        newData.push(row);
        this.setState({ tableData: newData, editingKey: '', rowID: row?.key }, () => {
          this.props.handleRowClick && this.props.handleRowClick(row);
          this.props.handleSave && this.props.handleSave(this.state.tableData);
        });
      }
    });
  }

  // 表单数据格式转换 - 保存时
  formDataFormatConversion = (fieldsValues) => {
    const { columns } = this.state;
    if (columns && columns.length > 0) {
      for (var i = 0; i < columns.length; i++) {
        for (var keys in fieldsValues) {
          if (columns[i].dataIndex === keys) {
            if (columns[i].inputType === 'SearchSelect') {
              // 修改了取修改后的值，没修改返回原值
              fieldsValues.detailitem = columns[i].detailitem || [];
              fieldsValues[columns[i].valueID] = Util.returnDataCccordingToAttributes(columns[i].detailitem, fieldsValues[keys], 'descripts')?.id;
            } else if (columns[i].inputType === 'Switch') { // 开关
              fieldsValues[keys] = fieldsValues[keys] ? 'Y' : 'N';
            } else if (columns[i].inputType === 'DatePicker' || columns[i].inputType === 'Date') {
              if (columns[i].showTime) {
                fieldsValues[keys] = fieldsValues[keys] && moment(fieldsValues[keys]).format(dateFormat); // 日期时间
              } else {
                fieldsValues[keys] = fieldsValues[keys] && moment(fieldsValues[keys]).format(dayFormat); // 日期
              }
            } else if (columns[i].inputType === 'Time') { // 时间
              fieldsValues[keys] = fieldsValues[keys] && moment(fieldsValues[keys]).format('HH:mm:ss');
            }
          }
        }
      }
    }
    return fieldsValues
  }

  // 表单数据转换 - 使用
  formDataConversion = fieldsValues => {
    let { columns } = this.state;
    if (columns && columns.length > 0) {
      for (var i = 0; i < columns.length; i++) {
        for (var keys in fieldsValues) {
          if (columns[i].dataIndex === keys) {
            if (columns[i].inputType === 'Switch') { // 开关
              fieldsValues[keys] = fieldsValues[keys] === 'Y' ? true : false;
            } else if (columns[i].inputType === 'DatePicker' || columns[i].inputType === 'Date') {
              if (columns[i].showTime === 'Y') {
                fieldsValues[keys] = fieldsValues[keys] ? moment(fieldsValues[keys], dateFormat) : undefined; // 日期时间
              } else {
                fieldsValues[keys] = fieldsValues[keys] ? moment(fieldsValues[keys], dayFormat) : undefined; // 日期
              }
            } else if (columns[i].inputType === 'Time') { // 时间
              fieldsValues[keys] = fieldsValues[keys] ? moment(fieldsValues[keys], 'HH:mm:ss') : undefined;
            }
          }
        }
      }
    }
    return fieldsValues
  }

  // 获取当前操作行的所在列
  getCurrentColumns = (record) => {
    const { columns } = this.state;
    let currentColumns = {};
    if (columns && columns.length > 0) {
      for (var i = 0; i < columns.length; i++) {
        for (var keys in record) {
          if (columns[i].dataIndex === keys) {
            currentColumns = columns[i];
            break;
          }
        }
      }
    }
    return currentColumns;
  }

  // 编辑
  handleEdit = (e, key, record) => {
    e.stopPropagation && e.stopPropagation();
    this.setState({ editingKey: key }, () => {
      this.props.editCurrentLine && this.props.editCurrentLine(this.formDataConversion(record)); // 编辑行时触发父组件方法
      // this.props.form.setFieldsValue && this.props.form.setFieldsValue(this.formDataConversion(record));
    });
  }

  /**
   * 删除 接口
   * deleteCode - 删除接口（code）
   * recordID - 传给后台的字段
   * rowIDName - 行数据对应的id
   * isSaveAnother - 是否另存
  */
  handleDelete = (record, e) => {
    e?.stopPropagation();
    let { deleteCode, recordID, rowIDName } = this.props;
    let isSaveAnother = this.props.isSaveAnother;
    if (recordID && (record[recordID] || (rowIDName && record[rowIDName])) && isSaveAnother !== "saveAnother") {
      if (this.props && this.props.handleDelete) { // 传入删除方法存在则走传入的，否则走统一的
        this.props.handleDelete(record, () => this.deleteRow(record.key));
      } else {
        let data = {
          params: [{
            [recordID]: rowIDName ? record[rowIDName] : record[recordID],
          }]
        }
        try {
          let res = React.$asyncPost(this, deleteCode, data);
          message.success(res && res.errorMessage ? res.errorMessage : '删除成功');
          this.deleteRow(record.key);
        } catch (error) {
          console.log(error)
        }
      }
    } else {
      this.deleteRow(record.key)
    }
  }

  // 本地删除数据
  deleteRow = (key) => {
    let tableData = JSON.parse(JSON.stringify(this.state.tableData));
    tableData = tableData.filter(item => item.key !== key);
    this.setState({ tableData: Util.addKeyValueToDataSource(tableData), rowID: '' }, () => {
      this.props.handleSave && this.props.handleSave(this.state.tableData);
    });
  }

  // 向外输出需要保存的数据
  handleSave = () => {
    let { tableData, editingKey, rowID } = this.state;
    return {
      tableData,
      editingKey,
      rowID
    };
  }

  // 重置
  resetFields = () => {
    this.setState({ tableData: [], editingKey: '' });
  }

  // 点击删除时阻止事件冒泡
  handlePopconfirm = (e) => {
    e.stopPropagation();
  };

  render() {
    let { title, desc, result, addBtnName, btnClick, tableFixed, totalWidth, isShowIcon, isDelete } = this.props;
    let { columns, userData, editingKey, tableData } = this.state;
    let tableOperation = {
      title: userData.language == 'EN' ? 'operating' : '操作',
      dataIndex: 'operation',
      width: '130px',
      align: 'center',
      fixed: tableFixed ? tableFixed : false,
      render: (text, record) => {
        const editable = this.isEditing(record);
        return editable ? (
          <span>
            <EditableContext.Consumer>
              {form => (
                <span
                  className="span"
                  onClick={(e) => this.handleRowSave(e, form, record.key)}
                >
                  {userData.language == 'EN' ? 'save' : '保存'}
                </span>
              )}
            </EditableContext.Consumer>
            <Divider type="vertical" />
            <Popconfirm
              title={userData.language == 'EN' ? 'Do you cancel editing?' : "是否取消编辑?"}
              okText={userData.language == 'EN' ? "Yes" : '是'}
              cancelText={userData.language == 'EN' ? "No" : '否'}
              onConfirm={(e) => this.handleCancel(record, e)}
              onCancel={this.handlePopconfirm}
              onClick={this.handlePopconfirm}
            >
              <span className="span" style={{ color: 'rgba(240,65,52,1)' }}> {userData.language == 'EN' ? 'cancel' : '取消'}</span>
            </Popconfirm>
          </span>
        ) : (
          <span>
            <a className="span" disabled={editingKey !== ''} onClick={(e) => this.handleEdit(e, record.key, record)}>
              {userData.language == 'EN' ? 'edit' : '编辑'}
            </a>
            {isDelete === 'N' ? '' : <Divider type="vertical" />}
            {isDelete === 'N' ? '' : (
              <Popconfirm
                title={userData.language == 'EN' ? 'Delete is not recoverable, are you sure you want to delete it?' : "删除不可恢复，你确定要删除吗?"}
                okText={userData.language == 'EN' ? "Yes" : '是'} cancelText={userData.language == 'EN' ? "No" : '否'}
                onConfirm={(e) => this.handleDelete(record, e)}
                onCancel={this.handlePopconfirm}
                onClick={this.handlePopconfirm}
              >
                <span className="span" style={{ color: 'rgba(240,65,52,1)' }}> {userData.language == 'EN' ? 'delete' : '删除'}</span>
              </Popconfirm>
            )}
          </span>
        );
      },
    }
    const tableComponents = {
      body: {
        cell: EditableCell,
      },
    };
    const filterColumns = [...columns, tableOperation].map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          ...col,
          record,
          editing: this.isEditing(record)
        }),
      };
    });
    return (
      <div className='inventory-item'>
        <div className='inventory-item-header'>
          <div className={isShowIcon === 'Y' ? 'card-title-left-icon' : '' + ' inventory-item-header-title'}>
            <div style={{ display: isShowIcon === 'Y' ? 'block' : 'none' }}></div>
            {title || ''}<span style={{ display: desc ? 'inline-block' : 'none' }}>（{desc}）</span>
          </div>
          <div className='inventory-item-header-desc'>
            <span style={{ display: result ? 'inline-block' : 'none' }}>预览：{result}</span>
            {addBtnName ? (
              <Button type="primary" ghost onClick={btnClick || null}>{addBtnName}</Button>
            ) : (
              <Button
                className="add-btn add-btn-nohover"
                icon="plus"
                onClick={this.handleAddTableData}
              >
                添加
              </Button>
            )}
          </div>
        </div>
        <EditableContext.Provider value={this.props.form}>
          <Table
            style={{ minHeight: '90px', marginBottom: '24px' }}
            components={tableComponents}
            bordered
            dataSource={tableData}
            columns={filterColumns}
            pagination={false}
            onRow={this.handleOnRow}
            rowClassName={this.setRowClassName}
            scroll={{ x: totalWidth ? totalWidth : false }}
            className="table-body-height table-empty"
          />
        </EditableContext.Provider>
      </div >
    )
  }
};

let UnitMaintenanceForm = Form.create()(UnitMaintenance);
export default UnitMaintenanceForm;